import { MessageBox, Message } from 'element-ui'
import Cookies from 'js-cookie'

export default (ctx, inject) => {
  const { app, env } = ctx
  const { $axios: axios, router } = app
  
  // create an axios instance
  const service = axios.create({
    baseURL: env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 30000 // request timeout
  })
  // request interceptor
  service.interceptors.request.use(
    config => {
      // do something before request is sent
      // if (store.getters.access_token) {
      //   // let each request carry token
      //   // ['Access-Token'] is a custom headers key
      //   config.headers['Access-Token'] = ''
      // }
      config.headers['Access-Token'] = Cookies.get('access_token')
      return config
    },
    error => {
      console.log('request error:', error) // for debug
      return Promise.reject(error)
    }
  )

  // response interceptor
  service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
    */
    response => {
      const res = response.data

      if (res.code !== 0) {
        if (res.code === 100003) {
          return res
        }
        if (res.message === '版本号已存在') {
          Message({
            message: res.message,
            type: 'error'
          })
        }
        if (res.code === 1017) { // 登录错误
          Message({
            message: res.message,
            type: 'error'
          })
        }
        if (res.code === 1015) { // token失效  expired
          console.log('token失效  expired:')
          router.replace('/')
          // this.$confirm('验证身份失效，是否重新登录？', '提示', {
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          // }).then(() => {
          //   router.replace('/')
          // }).catch(() => {
          //   this.$message({
          //     type: 'info',
          //     message: '已取消'
          //   })      
          // })
        }
        console.log('res.message:', res.message)
        return Promise.reject(new Error(res.message || 'Error'))
        
      } else {
        return res
      }
    },
    error => {
      console.log('error.response', error.response)
      // const err = error.response.data
      if (error.response.data.code === 4031001) { // token失效  expired
        console.log('process.env.VUE_APP_ENV >>>>>' + process.env.VUE_APP_ENV)
        if (process.env.VUE_APP_ENV === 'production') {
          MessageBox.confirm('身份验证失效，请重新进入', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            console.log('==============token expired==============')
          })
        } else {
          MessageBox.confirm('身份验证失效', '提示', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
 
          })
        }
      }
      return Promise.reject(err)
    }
  )
  ctx.$service = service
  inject('service', service)

  // 下载服务
  const dowloadService = axios.create({
    baseURL: env.VUE_APP_BASE_API, // url = base url + request url
    responseType: 'blob',
    timeout: 30000 // request timeout
  })

  dowloadService.interceptors.request.use(
    config => {
      config.headers['Access-Token'] = localStorage.getItem('access_token') || ''
      return config
    },
    error => {
      console.log(error) // for debug
      return Promise.reject(error)
    }
  )

  ctx.$dowloadService = dowloadService
  inject('dowloadService', dowloadService)
  
  
}
